<template>
	<uni-popup :mask-click="!isLoad" @maskClick="maskClick" type="bottom" ref="areaChoose">
		<view class="mian getHeight" id="main">
			<view class="top getHeight" id="top">
				<text class="topText">请选择所在地区</text>
				<image class="topImg" src="@/static/img/ccc.png" @click.stop="close" mode=""></image>
				<!-- // <text class="iconfont close" @click.stop="close">&#xe7fa;</text> -->
			</view>
			<view class="getHeight dingwei">
				<input v-model="str" @input="inputChange" type="text" placeholder="请输入">
				<view class="" @tap="repositioning" >
					<image src="/static/img/index/62.png" mode="widthFix"></image>
					<text style="color: blue;">重新定位</text>
				</view>
			</view>
			<scroll-view scroll-x="true" @scroll="scroll" :show-scrollbar="false" class="nav getHeight" id="nav"
				:scroll-into-view="scrollIntoView">
				<view @click="areaSelect(index)" class="nav-item" :class="{'nav-item-a':areaIndex == index}"
					v-for="(item, index) in str?[]:list" :key="index" :id="'area' + index">
					<text class="nav-item-text">{{ item }}</text>
				</view>
				<view class="bottomBorder" :style="'left:' + navBottomLeft + 'px'"></view>
			</scroll-view>
			<swiper class="swiper getHeight" :disable-touch="true" :current="current" style="flex:1;">
				<swiper-item v-for="(type, idx) in [1,2,3]" :key="idx" :id="'sw'+type">
					<scroll-view scroll-y="true" scroll-with-animation scroll-anchoring :scroll-into-view='id2'
						@scroll="scroll" :show-scrollbar="false" class="swiper-list">
						<view class="area-item" v-for="(item, index) in str?searchList:getList" :key="index"
							:id="'area' + index">
							<text class="area-item-text"
								:class="id == item._id+type ? 'area-item-id area-item-id-sticky': 'area-item-id'"
								:id='item._id+type'>{{ item._id }}</text>
							<view class="swiper-list2">
								<text
									:class="proCode == item2.code ? 'area-item-name area-item-name-a' : 'area-item-name'"
									@click="itemSelect(item2, idx)" v-for="(item2, index2) in item.data" :key="index2">
									<!-- 	<text class="iconfont"
										v-if="proCode == item2.code || cityCode == item2.code || disCode == item2.code">&#xe674;</text> -->
									{{ item2.name }}
								</text>
							</view>
						</view>
					</scroll-view>

				</swiper-item>
			</swiper>
			<view class="slider-right">
				<view class="slider-list">
					<text class="slider-item"
						v-for="(item, index) in (areaIndex == 0 ? provinceList : areaIndex == 1 ? cityList : areaIndex == 2 ? disList : townList)"
						:key="index" @click="sliderSelect(item._id +(areaIndex+1))">{{ item._id }}</text>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import provinceData from './static/city-china.js'
	import {
		setDialogView
	} from '@/utils/dialogView.ts'
	export default {
		name: 'area-choose',
		data() {
			return {
				list: ['请选择', '', ''],
				areaIndex: 0,
				navBottomLeft: 0,
				scrollIntoView: 'area0',
				code: '',
				provinceList: [], //省
				proCode: -1,
				cityList: [],
				cityCode: -1,
				disList: [],
				disCode: -1,
				townList: [],
				townCode: -1,
				swiperH: 300, //列表高
				current: 0, //当前滑块
				id: '', //地址编号A、B、C、...
				id2: '',
				scrollTopList: [{
					id: 'A',
					top: 0
				}],
				scrollTopListAll: {},
				provinceData: [],
				isLoad: false,
				str: '',
				searchList: []
			};
		},
		onLoad() {
			this.isLoad = true;
			setTimeout(() => {
				this.show()
			})
		},
		computed: {
			getList() {
				return this.areaIndex == 0 ? this.provinceList : this.areaIndex == 1 ? this.cityList : this.areaIndex ==
					2 ? this.disList : this.townList
			},
		},
		methods: {
			repositioning() {
				setDialogView('ACCESS_FINE_LOCATION').then((res) => {
					if (res == 1) {
						uni.showLoading({
							title: '加载中...',
							mask: true
						})

						uni.getLocation({
							type: 'gcj02',
							geocode: true,
							success: (res) => {
								uni.hideLoading()
								const {
									province,
									city,
									district
								} = res.address;
								let proCode = '';
								let cityCode = '';
								let disCode = '';
								provinceData.map((item) => {
									if (item.type == 0 && item.name == province) {
										proCode = item.code
									}
									if (item.type == 1 && item.name == city) {
										cityCode = item.code
									}
									if (item.type == 2 && item.name == district) {
										disCode = item.code
									}
								})
								if (this.isLoad) {
									uni.navigateBack()
									uni.$emit('mapAddress', {
										address: province + city + district,
										addressList: [province, city, district],
										proCode,
										cityCode,
										disCode
									})
								} else {
									this.$refs.areaChoose.close()

									this.$emit('confirm', {
										address: province + city + district,
										addressList: [province, city, district],
										proCode,
										cityCode,
										disCode
									})
								}

							},
							fail: () => {
								uni.showToast({
									title: '获取失败!',
									icon: 'none'
								})
							}
						})
					}
				})

			},
			inputChange() {
				const list = provinceData.filter((item) => {
					return item.name.indexOf(this.str) != -1;
				})
				this.searchList = this.groupByFirstLetter(list);
			},
			maskClick() {
				if (this.isLoad) {
					uni.navigateBack()
				}
			},
			close() {
				if (this.isLoad) {
					uni.navigateBack()
				} else {
					this.$refs.areaChoose.close()
				}
			},
			show() {
				this.$refs.areaChoose.open();

				this.provinceList = uni.getStorageSync('provinceList')
				if (!this.provinceList) {
					this.getData();
				} else {
					this.getScrollT(0, this.provinceList.length)
					this.current = 0;
					setTimeout(() => {
						this.areaSelect(0);
					}, 200)

				}

				setTimeout(() => {
					this.getSwiperH();
				}, 200);

			},
			onchange(e) {
				const value = e.detail.value;
			},
			scroll(e) {
				if (this.scrollTopList == undefined) return;
				this.scrollTopList.some((item, index) => {
					if (e.detail.scrollTop > item.top) {
						this.id = item.id
					}
				})
			},
			areaSelect(index) {
				this.$nextTick(() => {
					// 选中头部地址项
					this.areaIndex = index;
					this.current = index;
					//自动滚动
					this.scrollIntoView = 'area' + index;
					let widthAll = 0;
					for (let i = 0; i < index + 1; i++) {
						var query = uni.createSelectorQuery().in(this);
						var idView = '#area' + i;
						query.select(idView).boundingClientRect();
						query.exec(res => {
							if (i < index) {
								widthAll += res[0].width;
							}
							if (i == index) {
								this.navBottomLeft = widthAll + (res[0].width - uni.upx2px(60)) / 2;
							}
						});
					}
					this.scrollTopList = this.scrollTopListAll[index]
				})

			},
			sliderSelect(id) {
				this.id2 = id
			},
			getSwiperH() {
				// var query = uni.createSelectorQuery().in(this);
				// query
				// 	.selectAll('.getHeight')
				// 	.boundingClientRect()
				// 	.exec(res => {
				// 		if (res[0].length > 0) {

				// 			this.swiperH = res[0][0].height - res[0][1].height - res[0][2].height - res[0][3].height - uni.upx2px(20);
				// 		} else {
				// 			setTimeout(() => {
				// 				this.getSwiperH();
				// 			}, 200);
				// 		}
				// 	});
			},
			getScrollT(type, length) {
				var query = uni.createSelectorQuery().in(this);
				query.selectAll('#sw' + (type + 1) + ' .area-item-id')
					.boundingClientRect()
					.exec(res => {
						if (res[0].length == length) {
							this.scrollTopList = []
							let firstTop = res[0][0].top
							res[0].forEach((item, index) => {
								let obj = {
									id: item.id,
									top: item.top - firstTop
								}
								this.scrollTopList.push(obj)
							})
							this.scrollTopListAll[type] = this.scrollTopList
						} else {
							setTimeout(() => {
								this.getScrollT(type, length)
							}, 200)
						}

					});
			},
			getItem(code) {
				return provinceData.filter((item) => item.code == code)[0]
			},
			itemSelect(item, type) {
				if (this.str) {
					type = item.type;
				}
				switch (type) {
					case 0:
						this.proCode = item.code;
						break;
					case 1:
						if (this.str) {
							const proItem = this.getItem(item.parent_code);
							const plist = provinceData.filter((item1, index) => {
								return proItem.code == item1.parent_code
							})
							let list = this.groupByFirstLetter(plist)
							this.cityList = list;
							this.$set(this.list, 0, proItem.name);
							this.proCode = item.parent_code;
						}

						this.cityCode = item.code;
						break;
					case 2:
						if (this.str) {

							const proItem1 = this.getItem(item.parent_code);
							const plist1 = provinceData.filter((item1, index) => {
								return proItem1.code == item1.parent_code
							})
							let list = this.groupByFirstLetter(plist1)
							this.disList = list;
							this.$set(this.list, 1, proItem1.name);
							this.cityCode = item.parent_code;


							const proItem = this.getItem(proItem1.parent_code);
							const plist = provinceData.filter((item1, index) => {
								return proItem.code == item1.parent_code
							})
							let list1 = this.groupByFirstLetter(plist)
							this.cityList = list1;
							this.$set(this.list, 0, proItem.name);
							this.proCode = proItem.code;
						}
						this.disCode = item.code;
						break;
					case 3:
						this.townCode = item.code;
						break;
					default:
						break;
				}
				if (this.str) {
					this.str = ''
				}
				this.list.forEach((item2, index2) => {
					if (index2 == type) {
						this.$set(this.list, type, item.name);
						if (index2 < 2) {
							this.$set(this.list, type + 1, '请选择');
							this.getData(item.code, type + 1);
						} else {
							setTimeout(() => {
								this.areaSelect(type);
							}, 200);
						}
					}
					if (index2 > type + 1) {
						this.$set(this.list, index2, '');
					}
				});
				if (type == 2) {
					if (this.isLoad) {
						uni.navigateBack()
						uni.$emit('mapAddress', {
							address: this.list.join(''),
							addressList: this.list,
							proCode: this.proCode,
							cityCode: this.cityCode,
							disCode: this.disCode
						})
					} else {
						this.$refs.areaChoose.close()
						console.log({
							address: this.list.join(''),
							addressList: this.list,
							proCode: this.proCode,
							cityCode: this.cityCode,
							disCode: this.disCode
						})
						this.$emit('confirm', {
							address: this.list.join(''),
							addressList: this.list,
							proCode: this.proCode,
							cityCode: this.cityCode,
							disCode: this.disCode
						})
					}

				}

			},

			groupByFirstLetter(data) {
				// 先进行分组
				let grouped = data.reduce((acc, item) => {
					let letter = item.first_letter;
					let group = {
						_id: letter,
						data: []
					};

					if (!acc.find(g => g._id === letter)) {
						acc.push(group);
					} else {
						group = acc.find(g => g._id === letter);
					}

					group.data.push(item);
					return acc;
				}, []);

				// 对分组进行排序
				grouped.sort((a, b) => a._id.localeCompare(b._id));

				return grouped;
			},
			getData(code = '', type = 0) {
				const plist = provinceData.filter((item, index) => {
					if (type == 0) {
						return item.type == type
					} else {
						return item.parent_code == code && item.type == type
					}
				})
				let list = this.groupByFirstLetter(plist)

				switch (type) {
					case 0:
						this.provinceList = list;
						uni.setStorageSync('provinceList', list)
						break;
					case 1:
						this.cityList = list;
						break;
					case 2:
						this.disList = list;
						break;
					case 3:
						this.townList = list;
						break;
					default:
						break;
				}
				if (list.length > 0) {
					this.getScrollT(type, list.length)
				}
				this.current = type;
				this.areaSelect(type);
			}
		}
	};
</script>


<style lang="scss">
	/*每个页面公共css */
	@font-face {
		font-family: 'iconfont';
		src: url('./static/iconfont/iconfont.ttf') format('truetype');
	}

	:deep(page) {
		background: transparent;
	}

	.iconfont {
		font-family: iconfont;
	}

	.mian .top .topImg {
		width: 30rpx;
		height: 30rpx;
	}

	.iconfont {
		font-size: 40rpx;
	}

	.close {
		padding: 40rpx 30rpx 30rpx;
		z-index: 3;

	}

	.topText {
		font-size: 32rpx;
		font-weight: bold;
	}

	.mian .top {
		flex-direction: row;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-left: 30rpx;

		padding: 30rpx;






	}

	.bottomBorder {
		position: absolute;
		width: 60rpx;
		height: 6rpx;
		background: linear-gradient(to right, rgba(255, 0, 0, 1), rgba(255, 0, 0, 0.5));
		bottom: 5rpx;
		left: 0rpx;
		transition: left 0.5s ease;
	}

	.nav-item {
		padding: 10rpx 20rpx;
		display: inline-block;
		text-align: center;
	}

	.nav-item-text {
		font-size: 28rpx;
	}

	.nav-item-a .nav-item-text {
		color: rgb(201, 22, 35) !important;
		// position: relative;
	}

	.nav {
		white-space: nowrap;
		width: 100%;
		position: relative;
		padding: 0rpx 20rpx;
		// background-color:#ddd;

	}



	.area-item-id {
		padding: 20rpx 44rpx;
		border-bottom: 1rpx solid #f0ecf2;
		font-weight: bold;
		display: block;
	}

	.area-item-id-sticky {
		position: sticky;
		top: 0;
		background-color: #FFFFFF;
		transition: all 0.1s;
		z-index: 9;
	}

	.area-item {
		font-size: 30rpx;
	}

	.area-item-text {
		font-size: 30rpx;
	}

	.area-item-name {
		padding: 20rpx 40rpx 0;
		font-weight: 400;


	}

	.area-item-name-a {
		color: rgb(201, 22, 35);
	}

	.iconfont {
		color: rgb(201, 22, 35);
		margin-right: 10rpx;
	}

	.swiper-list2 {
		display: flex;
		flex-direction: column;

	}

	.swiper-list {
		height: 100%;
		display: flex;
		flex-direction: column;
		position: relative;



	}

	.swiper {
		height: 1000rpx;
		margin-top: 20rpx;


	}

	.slider-list {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #ebe8ee;
		border-radius: 20rpx;
	}

	.slider-right {
		position: absolute;
		right: 0rpx;
		top: 80rpx;
		bottom: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx;




	}

	.slider-item {
		padding: 10rpx 10rpx;
		font-size: 26rpx;
		color: #24292E;
	}

	.slider-item:first-child {
		padding-top: 20rpx;
	}

	.slider-item:last-child {
		padding-bottom: 20rpx;
	}

	.mian {
		height: 80vh;
		width: 100%;
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
		position: relative;
		display: flex;
		padding-bottom: 20rpx;
		flex-direction: column;

	}

	.dingwei input {
		flex: 1;
		margin-right: 20rpx;
		margin-left: 32rpx;
	}

	.dingwei {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.dingwei view {
		display: flex;
		align-items: center;
		color: #6B64D3;
		font-size: 28rpx;
		padding: 20rpx;
	}

	.dingwei image {
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
	}
</style>